﻿/* DisplayModule interface. */
var DisplayModule = new Interface("DisplayModule", ["append", "remove", "clear"]);

var ListDisplay = function (id, parent) {
    this.list = document.createElement('ul');
    this.list.id = id;
    parent.appendChild(this.list);
};

ListDisplay.prototype = {
    append: function (text) {
        var item = document.createElement('li');
        item.innerHTML = text;
        this.list.appendChild(item);
        return item;
    },
    remove: function (item) {
        this.list.removeChild(item);
    },
    clear: function () {
        this.list.innerHTML = '';
    }
};

var conf = {
    id: 'ScottGu_Blog',
    feedUrl: 'http://weblogs.asp.net/scottgu/rss.aspx',
    updateInterval: '60',// In seconds.
    parent: $('blog')
};

var FeedReader = function (display, xhr, conf) {
    this.display = display;
    this.xhr = xhr;
    this.conf = conf;

    this.startUpdates();
};

FeedReader.prototype = {
    fetchFeed: function () {
        var _this = this;
        var callback = {
            success: function (text, xml) { _this.parseFeed(text, xml); },
            failure: function (status) { _this.showError(status); }
        };
        this.xhr.request('GET', 'FeedProxy.aspx?feed=' + this.conf.feedUrl, callback);
    },
    parseFeed: function (responseText, responseXML) {
        console.log(responseXML);

        //var parser = new DOMParser();
        //var xmlDoc = parser.parseFromString(responseText, "application/xml");
        //console.log(xmlDoc);

        this.display.clear();
        var items = responseXML.getElementsByTagName('item');
        for (var i = 0, len = items.length; i < len; i++) {
            var title = items[i].getElementsByTagName('title')[0];
            var link = items[i].getElementsByTagName('link')[0];
            this.display.append('<a href="' + link.firstChild.data + '">' + title.firstChild.data + '</a>');
        }
    },
    showError: function (statusCode) {
        this.display.clear();
        this.display.append('Error fetching feed.');
    },
    stopUpdates: function () {
        clearInterval(this.interval);
    },
    startUpdates: function () {
        this.fetchFeed();
        var _this = this;
        this.interval = setInterval(function () {
            _this.fetchFeed();
        }, conf.updateInterval * 1000);
    }
};